package gui.windows.components;

import java.io.File;

import javax.swing.DefaultListModel;
import javax.swing.JList;

@SuppressWarnings("serial")
public class FileList extends JList<File> {
	String dir;
	String extention;
	DefaultListModel<File> modelList;
	@SuppressWarnings("unchecked")
	public FileList(String dir,String extention){
		this.dir = dir;
		this.extention = extention;
		this.setCellRenderer(new FileCellRenderer());
		
		File folder = new File(dir);
		modelList = new DefaultListModel<File>();
		this.setModel(modelList);
		if(!folder.exists())
			return;
		  
		File[] listOfFiles = folder.listFiles(); 
		 
		for (int i = 0; i < listOfFiles.length; i++) {
		 
		 if (listOfFiles[i].isFile()) {
			 String file = listOfFiles[i].getName();
		     if (extention.startsWith(".*") || file.endsWith(extention) || file.endsWith(extention.toUpperCase())){
		          modelList.addElement(listOfFiles[i]);
		     }
		   }
		}
	}
	public void refreshList(){
		modelList.clear();
		File folder = new File(dir);
		if(!folder.exists())
			return;
		  
		File[] listOfFiles = folder.listFiles(); 
		 
		for (int i = 0; i < listOfFiles.length; i++) {
		 
		 if (listOfFiles[i].isFile()) {
			 String file = listOfFiles[i].getName();
			 System.out.println(file);
		     if (extention.startsWith(".*") || file.endsWith(extention) || file.endsWith(extention.toUpperCase())){
		          modelList.addElement(listOfFiles[i]);
		     }
		   }
		}
	}
	
	public boolean deleteSelected(){
	if(this.getSelectedValue() == null)
		return false;
	File file = this.getSelectedValue();
	if(file.delete()){
		modelList.removeElement(file);
		return true;
	}else return false;
	}
}
